﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Extension;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CoordinateTransformService
{
    public partial class CoordinateTransformService : ServiceBase
    {
        public CoordinateTransformService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _timer = new System.Timers.Timer();
            _timer.Interval = IntervalTime;  //设置计时器事件间隔执行时间默认n分钟执行一次
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(CoordinateTransformReverse);
            _timer.Enabled = true;
        }


        protected override void OnStop()
        {
            this._timer.Enabled = false;
            _recevie = false;
        }

        /// <summary>
        /// 执行中奖表坐标转换
        /// </summary>
        public void CoordinateTransformReverse(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (_recevie)
            {
                _fileLog.Info(
               "LocationWindowsService | CoordinateTransformReverse  |等待上一个线程结束");
            }
            List<Shops> shopsRecord = ShopsBLL.Instance.GetModelList(string.Format("  Latitude is not null and Longitude is not null and Latitude!='' and Longitude!='' AND IsCoordinateTransform=0 "));
            if (shopsRecord == null || shopsRecord.Count < 1)
            {
                _fileLog.Info(
                              "LocationWindowsService | CoordinateTransformReverse  :暂无数据,等待重新扫描.....");
                Thread.Sleep(60000 * 10);//没有数据的时候休眠一会
                return;
            }
            _recevie = true;
            _fileLog.Info(
                     "LocationWindowsService | CoordinateTransformReverse  |现有: " +
                     shopsRecord.Count() + "条记录正在处理");
            foreach (var item in shopsRecord)
            {
                try
                {
                    double[] coordinateStr = CoordinateTransform.BD_WG84(double.Parse(item.Longitude), double.Parse(item.Latitude));
                    if (coordinateStr != null && coordinateStr.Count() > 0)
                    {
                        _fileLog.Info(
       "LocationWindowsService | CoordinateTransformReverse  |原始坐标: id:" +
      item.Id + ",Longitude:" + item.Longitude + ",Latitude:" + item.Latitude);
                        item.Longitude = coordinateStr[0].ToString();
                        item.Latitude = coordinateStr[1].ToString();
                        item.IsCoordinateTransform = true;
                        if (!ShopsBLL.Instance.Update(item))
                        {
                            _fileLog.Info(
                                "LocationWindowsService | CoordinateTransformReverse  |更新失败,id: " +
                                item.Id + "" );
                        }
                    }
                    else
                    {
                        _fileLog.Info(
                        "LocationWindowsService | CoordinateTransformReverse  |接口调用失败,id: " +item.Id );
                    }
                }
                catch (Exception ex)
                {
                    _fileLog.Info(
                 "LocationWindowsService | CoordinateTransformReverse  |接口异常失败,id: " +
                  item.Id + ",Exception:" + ex.Message);
                }

                Thread.Sleep(500);
            }
            _recevie = false;
        }
        public static LocationPosition ExecutiveCoordinateTransformation(string latitude, string longitude)
        {
            try
            {
                string url = string.Format("http://api.map.baidu.com/geoconv/v1/?coords={0},{1}&from={2}&to=5&ak={3}", longitude, latitude, 5
                                                  , "BFd2961fded52d7fcb3c01ad0d1623b2");
                var result = HttpClientHelper.Request(url, "", "GET");
                LocationPosition model = ConversionData(result);
                return model;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public static LocationPosition ConversionData(string jsonResult)
        {
            LocationPosition model = new LocationPosition();
            JObject jsonData = (JObject)JsonConvert.DeserializeObject(jsonResult);
            if (jsonData != null)
            {
                model.Status = jsonData["status"].ToString();
                if (model.Status == "0")
                {
                    if (jsonData["result"] != null)
                    {
                        Location locationModel = new Location();
                        if (jsonData["result"][0]["x"] != null)
                        {
                            locationModel.lng = jsonData["result"][0]["x"].ToString();
                        }
                        if (jsonData["result"][0]["y"] != null)
                        {
                            locationModel.Lat = jsonData["result"][0]["y"].ToString();
                        }
                        model.Locations = locationModel;
                    }
                }
                return model;
            }
            return null;
        }
    }
}
